require 'sqlexec'

class RowInserter
  def initialize(sqlexec, tbname)
    @tbname = tbname
    @sqlexec = sqlexec
  end
  private
  def getrand(len)
    (('a'..'z').to_a + ('A'..'Z').to_a).sort_by{rand}[0, len]
  end
  def getseq(start, repeat)
    isFixnum = start.match(/^(\d+)$/).to_s == "" ? false : true
    if(isFixnum)
      return (start.to_i + repeat).to_s
    else
      obj = ('a'..'z').to_a
      return obj[(obj.index(start)+repeat)%obj.size]
    end
  end
  def parser(values, repeat)
    values.map do |val|
      val.class.to_s == "String" ? val = "'#{val}'" : val
      if val.respond_to?('gsub')
        val.gsub(/\[(\w+):(\w+)\]/) do |match|
          cmd, param = match.scan(/\[(\w+):(\w+)\]/).flatten
          case cmd
          when 'r' 
            match = getrand(param.to_i)
          when 's'
            match = getseq(param, repeat) 
          end
        end
      else
        val
      end
    end
  end
  public
  def ins(targets, values, repeat)
    queries = []
    repeat.times do |ln|
      queries.push "INSERT INTO #{@tbname.upcase}(#{targets.join(', ').to_s.upcase}) VALUES(#{parser(values, ln).join(', ').to_s})\r\n"
    end
    puts queries.to_s 
    @sqlexec.ddlquery queries.to_s
  end
end
